export default class HTMLTableOfContentsGenerator {
    private readonly headings: HTMLHeadingElement[];

    constructor() {
        this.headings = Array.from(document.querySelectorAll('h1, h2, h3, h4, h5, h6'));
    }

    generateTableOfContents(): string {
        let tocHtml = '<ul>';

        for (const heading of this.headings) {
            const headingText = heading.textContent || '';
            const headingId = headingText.toLowerCase().replace(/\s+/g, '-');

            tocHtml += `<li><a href="#${headingId}">${headingText}</a></li>`;
            heading.id = headingId;
        }

        tocHtml += '</ul>';
        return tocHtml;
    }
}

/**
 * 二分查找，没找到就返回插入位置左侧的索引
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
export function searchInsert(nums: number[], target: number): number {
    let left = 0;
    let right = nums.length - 1;

    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (nums[mid] === target) {
            return mid;
        } else if (nums[mid] > target) {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return right;
}
